package io.adrainty.algorithm.leetcode.normal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @link <a href="https://leetcode.cn/problems/find-longest-special-substring-that-occurs-thrice-ii/description/">...</a>
 * @author adrainty
 * @version v1.0.0
 * @since 2024/5/2 22:34
 */

@SuppressWarnings("unchecked")
public class Solution2982 {

    public int maximumLength(String s) {
        char[] cs = s.toCharArray();
        List<Integer>[] groups = new ArrayList[26];
        Arrays.setAll(groups, i -> new ArrayList<>());
        int cnt = 0;
        for (int i = 0; i < cs.length; i++) {
            cnt++;
            if (i == cs.length - 1 || cs[i] != cs[i + 1]) {
                groups[cs[i] - 'a'].add(cnt); // 统计连续字符长度
                cnt = 0;
            }
        }

        int ans = 0;
        for (List<Integer> a : groups) {
            if (a.isEmpty()) continue;
            a.sort(Collections.reverseOrder());
            a.add(0);
            a.add(0); // 假设还有两个空串
            ans = Math.max(ans, Math.max(a.get(0) - 2, Math.max(Math.min(a.get(0) - 1, a.get(1)), a.get(2))));
        }
        return ans > 0 ? ans : -1;
    }

}
